export default {
  created(el, binding) {
    if (typeof binding.value !== 'function') {
      throw new Error('callback must be a function');
    }

    let pressTimer = null;
    let isLongPressActive = false; // 标记是否处于长按状态
    let activeElement = null; // 记录当前处于长按状态的元素
    let deleteButton = null; // 删除按钮元素

    const start = (e) => {
      if (e.type === 'click' && e.button !== 0) return;
      if (pressTimer === null) {
        pressTimer = setTimeout(() => {
          handler(e);
        }, 2000); // 长按时间设置为2秒
      }
    };

    const cancel = () => {
      clearTimeout(pressTimer);
      pressTimer = null;
    };

    const handler = (e) => {
      el.classList.add('longpress-active'); // 添加用于显示阴影和按钮的类
      isLongPressActive = true; // 设置为长按状态
      activeElement = el; // 更新当前激活的元素
      deleteButton = el.querySelector('.delete-btn'); // 获取删除按钮
      document.addEventListener('click', handleClickOutside); // 监听文档点击事件
      binding.value(e); // 调用传入的回调函数
    };

    const handleClickOutside = (event) => {
      if (isLongPressActive && activeElement && !activeElement.contains(event.target) && (deleteButton && !deleteButton.contains(event.target))) { // 如果点击发生在目标元素或删除按钮之外
        event.stopImmediatePropagation(); // 阻止事件冒泡
        event.preventDefault(); // 取消默认动作
        activeElement.classList.remove('longpress-active'); // 移除样式类以取消长按效果
        document.removeEventListener('click', handleClickOutside); // 移除监听器
        activeElement = null; // 清空记录
        isLongPressActive = false; // 结束长按状态
      }
    };

    const endLongPress = () => {
      isLongPressActive = false; // 结束长按状态
      activeElement = null; // 清空激活元素
    };

    el.addEventListener('mousedown', start);
    el.addEventListener('touchstart', start);

    el.addEventListener('click', cancel);
    el.addEventListener('mouseout', cancel);
    el.addEventListener('touchend', endLongPress);
    el.addEventListener('touchcancel', endLongPress);
  },
  unbind(el) {
    el.classList.remove('longpress-active');
    document.removeEventListener('click', handleClickOutside); // 确保移除全局监听器
  }
}